package com.aaa.service.impl;

import com.aaa.dao.BookShopDao;
import com.aaa.service.BookShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description:
 * @author:LiWei
 * @date:2022年11月14日19:04
 */
@Service
public class BookShopServiceImpl implements BookShopService {

    @Autowired
    private BookShopDao bookShopDao;

    //线程并发问题: 库存超卖。---业务层 业务逻辑比较复杂时，需要调用多个dao层代码
    //propagation: 定义事务的传播属性。默认为REQUEIRES.
    //rollbackFor:指定哪些异常回滚。
    //noRollbackFor:指定哪些异常类型不会滚。
    //timeout = 2: 如果代码执行时间超过2秒 则事务也会回滚

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED,
            timeout = 1
    )
    public void purchase(String isbn, String username) {
        //根据图书编号查询图书对应的价格
        int price = bookShopDao.findBookPriceByIsbn(isbn);
        //判断库存
        int stock = bookShopDao.findStockByIsbn(isbn);
        if (stock > 0) {
            //修改库存
            bookShopDao.updateBookStock(isbn);
        } else {
            throw new RuntimeException("图书编号为:" + isbn + ";库存不足");
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //判断余额
        int balance = bookShopDao.findBalanceByUsername(username);
        if (balance >= price) {
            //修改账户余额
            bookShopDao.updateAccount(username, price);
        } else {
            throw new RuntimeException("账户为:" + username + ";余额不足.");
        }

    }
}
